package app

import (
	"fmt"
	"strings"

	"github.com/spf13/cobra"
)

func HelpCommand() ApplyOption {
	return Option(func(c *cobra.Command) {
		c.SetHelpCommand(New(OptionGroup{
			Use("help [command]"),
			Run(func(c *cobra.Command, args []string) {
				cmd, _, e := c.Root().Find(args)
				if cmd == nil || e != nil {
					c.Printf("Unknown help topic %#q\n", args)
					cobra.CheckErr(c.Root().Usage())
				} else {
					cmd.InitDefaultHelpFlag()
					cobra.CheckErr(cmd.Help())
				}
			}),
			Option(func(c *cobra.Command) {
				c.ValidArgsFunction = func(c *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
					var completions []string
					cmd, _, e := c.Root().Find(args)
					if e != nil {
						return nil, cobra.ShellCompDirectiveNoFileComp
					}
					if cmd == nil {
						cmd = c.Root()
					}
					for _, subCmd := range cmd.Commands() {
						if subCmd.IsAvailableCommand() {
							if strings.HasPrefix(subCmd.Name(), toComplete) {
								completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))
							}
						}
					}
					return completions, cobra.ShellCompDirectiveNoFileComp
				}
			}),
		}))
	})
}
